package com.yudean.esb.service.impl.erp;

import com.yudean.esb.dao.erp.ErpClientLogDao;
import com.yudean.esb.domain.erp.ErpClientLog;
import com.yudean.esb.service.ErpClientService;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.PhaseInterceptorChain;
import org.apache.cxf.transport.http.AbstractHTTPDestination;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service("ErpClientServiceImpl")
@Scope("prototype")
public class ErpClientServiceImpl implements ErpClientService {

    private final static Logger log = LoggerFactory.getLogger(ErpClientServiceImpl.class);

    @Resource
    private ErpClientLogDao erpClientLogDao;

    @Override
    public void addErpClientLog(String token) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String currentTime = dateFormat.format(date);
        Message message = PhaseInterceptorChain.getCurrentMessage();
        HttpServletRequest httpServletRequest = (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST);
        String ip = httpServletRequest.getRemoteAddr();
        String url = String.valueOf(httpServletRequest.getRequestURL());

        ErpClientLog erpClientLog = new ErpClientLog();
        erpClientLog.setClientIp(ip);
        erpClientLog.setUrl(url);
        erpClientLog.setToken(token);
        erpClientLog.setCreateTime(currentTime);
        List<ErpClientLog> clientLogLists = erpClientLogDao.getClientLog(erpClientLog);
        if (null == clientLogLists || clientLogLists.size() < 1) {
            log.info("ERP interface insert  url is:{},  user ip is:{}, user token is:{}", url, ip, token);
            erpClientLogDao.insertClientLog(erpClientLog);
        }
        log.info("ERP interface url is:{},  user ip is:{}, user token is:{},currentTime is:{}", url, ip, token, currentTime);
    }

}
